package com.mediacloud.app.newsmodule.fragment.baoliao.frag;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.mediacloud.app.model.component.ComponentItem;
import com.mediacloud.app.model.fragment.BaseFragment;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.NewBaoLiaoListModel;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.fragment.baoliao.OnItemClickListener;
import com.mediacloud.app.newsmodule.fragment.baoliao.activity.BaoLiaoDetailActivity;
import com.mediacloud.app.newsmodule.fragment.baoliao.adapter.MyBaoLiaoListAdapter;
import com.mediacloud.app.newsmodule.fragment.baoliao.api.FacadeApi;
import com.mediacloud.app.newsmodule.fragment.baoliao.api.SpiderCmsApi;
import com.mediacloud.app.newsmodule.fragment.baoliao.api.SpiderCmsLowApi;
import com.mediacloud.app.newsmodule.model.baoliao.list.list.BaoNiaoListItem;
import com.mediacloud.app.newsmodule.utils.BaoLiaoBlockListUtils;
import com.mediacloud.app.newsmodule.utils.ComponentClickUtils;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.user.model.UserInfo;
import com.mediacloud.app.user.utils.RxUtils;
import com.mediacloud.app.view.XSmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by Yoake on 2018/8/24.
 */

public class MyBaoLiaoListFragment extends BaseFragment implements OnRefreshListener, OnLoadMoreListener, OnItemClickListener {
    private XSmartRefreshLayout ptrLayout;
    private RecyclerView recyclerView;
    private MyBaoLiaoListAdapter adapter;
    private String status;
    private int page = 1;
    private int perPage = 20;
    private TextView tvBaoLiaoJump;
    /**
     * 跳转导航的数据结构
     */
    private ComponentItem componentItem = new ComponentItem();

    @Override
    public int getLayoutResID() {
        return R.layout.my_baoliao_list_layout;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null != getArguments()) {
            status = getArguments().getString("status");

        }
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void initView() {
        initView(mRootView);
    }

    @Override
    protected void initOther() {
        super.initOther();
        getListData();
    }

    public static MyBaoLiaoListFragment newInstance(String status) {
        Bundle args = new Bundle();
        args.putString("status", status);
        MyBaoLiaoListFragment fragment = new MyBaoLiaoListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    private void initView(View view) {
        recyclerView = view.findViewById(R.id.mRecyclerView);
        recyclerView.setItemAnimator(null);//置空缺陷忽略
        ptrLayout = view.findViewById(R.id.ptrLayout);
        ptrLayout.setEnableRefresh(true);
        ptrLayout.setEnableLoadMore(true);
        ptrLayout.setOnRefreshListener(this);
        ptrLayout.setOnLoadMoreListener(this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        adapter = new MyBaoLiaoListAdapter(getActivity(), this);
        recyclerView.setAdapter(adapter);
        tvBaoLiaoJump = view.findViewById(R.id.tv_bao_liao_jump);
        tvBaoLiaoJump.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ComponentClickUtils.OpenItemComponent(getContext(), componentItem, null);
            }
        });
        Pattern pattern = Pattern.compile("(?i)" + "点击查看更多");
        String title = "已无更多我的爆料，点击查看更多其他爆料";
        Matcher matcher = pattern.matcher(title);
        Map<String, String> map = new HashMap<>();
        while (matcher.find()) {
            map.put(matcher.group(), matcher.group());
        }
        Set<Map.Entry<String, String>> e = map.entrySet();
        Iterator<Map.Entry<String, String>> iterator = e.iterator();
        while (iterator.hasNext()) {
            String replaceString = iterator.next().getKey();
            title = title.replaceAll(replaceString, replaceString(replaceString));
        }
        tvBaoLiaoJump.setText(Html.fromHtml(title));
        showStateView(TYPE_LOADING, false);
        loadingView = mRootView.findViewById(R.id.loadingLayout);
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) loadingView.getLayoutParams();
        params.addRule(RelativeLayout.ABOVE, R.id.tv_bao_liao_jump);
        loadingView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!currentState.equals(TYPE_LOADING)) {
                    page = 1;
                    showStateView(TYPE_LOADING, false);
                    getListData();
                }
            }
        });
    }

    private void buildComponentItem() {

    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        ptrLayout.setEnableLoadMore(false);
        ptrLayout.setEnableRefresh(false);
        page++;
        getListData();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        ptrLayout.setEnableLoadMore(false);
        ptrLayout.setEnableRefresh(false);
        page = 1;
        getListData();
    }

    private String ids = "";

    private void getListData() {
        UserInfo userInfo = UserInfo.getUserInfo(requireContext());
        JSONObject object = new JSONObject();
        try {
            object.put("tipUserId", userInfo.getUserid());
            object.put("moduleType", 1);
            object.put("pageNumber", page);
            object.put("pageSize", perPage);
            object.put("checkStatus", status);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), object.toString());
        SpiderCmsApi.getSpiderCmsApi(getContext())
                .getTipoffFindPageList(getString(R.string.tenantid), body)
                .compose(RxUtils.schedulersTransformer())
                .subscribe(new Observer<NewBaoLiaoListModel>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull NewBaoLiaoListModel model) {
                        Log.e(TAG, "" + model);
                        ptrLayout.finishRefresh();
                        ptrLayout.finishLoadMore();

                        ptrLayout.setEnableRefresh(true);
                        try {
                            if (model.isSuccess()) {
                                boolean haveMore = model.getData().isHasNextPage();
                                ptrLayout.setEnableLoadMore(haveMore);
                                ids = "";
                                for (int i = 0; i < model.getData().getPageRecords().size(); i++) {
                                    if (!TextUtils.isEmpty(ids)) {
                                        ids += "," + model.getData().getPageRecords().get(i).getId();
                                    } else {
                                        ids += model.getData().getPageRecords().get(i).getId();
                                    }
                                }
                                FacadeApi.getSpiderCmsApiJson(getActivity())
                                        .getFaceData(ids, 5)
                                        .subscribeOn(Schedulers.io())
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(new Observer<JSONObject>() {
                                            @Override
                                            public void onSubscribe(Disposable d) {

                                            }

                                            @Override
                                            public void onNext(JSONObject jsonObject) {
                                                if (jsonObject == null) {
                                                    return;
                                                }
                                                boolean state = jsonObject.optBoolean("state", false);
                                                if (state) {
                                                    JSONArray meta = jsonObject.optJSONArray("data");
                                                    try {
                                                        for (int i = 0; i < model.getData().getPageRecords().size(); i++) {
                                                            if (meta != null) {
                                                                for (int j = 0; j < meta.length(); j++) {
                                                                    if (model.getData().getPageRecords().get(i).getId() == ((JSONObject) meta.get(i)).optLong("id")) {
                                                                        model.getData().getPageRecords().get(i).setHitcount(((JSONObject) meta.get(i)).optInt("commentCount"));
                                                                    }
                                                                    break;
                                                                }
                                                            }
                                                        }
                                                    } catch (JSONException e) {
                                                        e.printStackTrace();
                                                    }
                                                }
                                                if (page == 1) {
                                                    adapter.setList(model.getData().getPageRecords());
                                                    if (model.getData() == null
                                                            || model.getData().getPageRecords() == null
                                                            || model.getData().getPageRecords().size() == 0) {
                                                        showStateView(TYPE_NO_CONTENT, false);
                                                        //数据为空
                                                        if (haveMore) {
                                                            tvBaoLiaoJump.setVisibility(View.GONE);
                                                        } else {
                                                            tvBaoLiaoJump.setVisibility(View.GONE);
                                                        }
                                                    } else {
                                                        closeStateView();
                                                    }
                                                } else {
                                                    adapter.addList(model.getData().getPageRecords());
                                                }

                                            }

                                            @Override
                                            public void onError(Throwable e) {
                                                if (page == 1) {
                                                    adapter.setList(model.getData().getPageRecords());
                                                    if (model.getData() == null
                                                            || model.getData().getPageRecords() == null
                                                            || model.getData().getPageRecords().size() == 0) {
                                                        showStateView(TYPE_NO_CONTENT, false);
                                                        //数据为空
                                                        if (haveMore) {
                                                            tvBaoLiaoJump.setVisibility(View.GONE);
                                                        } else {
                                                            tvBaoLiaoJump.setVisibility(View.GONE);
                                                        }
                                                    } else {
                                                        closeStateView();
                                                    }
                                                } else {
                                                    adapter.addList(model.getData().getPageRecords());
                                                }
                                            }

                                            @Override
                                            public void onComplete() {
                                            }
                                        });


//                                componentItem.setNavigate_id(Integer.parseInt(model.getData().getMore_tipoff().getTurn_more_tipoff_navigateid()));
//                                String navigate = "{navigate:"+model.getData().getMore_tipoff().getNavigate()+"}";
//                                componentItem.orginDataObject = new JSONObject(navigate);
//                                componentItem.title = componentItem.orginDataObject.optJSONObject("navigate").getString("name");

                            } else {
                                showStateView(TYPE_NO_CONTENT, false);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        ptrLayout.setEnableLoadMore(true);
                        ptrLayout.setEnableRefresh(true);
                        ptrLayout.finishRefresh();
                        ptrLayout.finishLoadMore();
                        if (page == 1) {
                            showStateView(TYPE_NET_NOT_GIVE_FORCE, false);
                            tvBaoLiaoJump.setVisibility(View.GONE);
                        } else {
                            closeStateView();
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });

//        DataInvokeUtil.getZiMeiTiApi().getMyTipOff("45691098319814778", status, page, perPage).compose(TransUtils.fastJSonTransform(BaoLiaoListModel.class))
//                .compose(RxUtils.<BaoLiaoListModel>schedulersTransformer())
//                .subscribe(new BaseController().new BaseObserver<BaoLiaoListModel>() {
//                    @Override
//                    public void onNext(BaoLiaoListModel model) {
//                        ptrLayout.finishRefresh();
//                        ptrLayout.finishLoadMore();
//
//                        ptrLayout.setEnableRefresh(true);
//                        try {
//                            if (model.isState()) {
//                                boolean haveMore = model.getData().getPaging().getLastPage() > model.getData().getPaging().getCurrentPage();
//                                ptrLayout.setEnableLoadMore(haveMore);
//                                if (page == 1) {
//                                    if(model.getData() == null
//                                            || model.getData().getMeta()== null
//                                            || model.getData().getMeta().size() == 0){
//                                        showStateView(TYPE_NO_CONTENT,false);
//                                        //数据为空
//                                        if(model.getData().getPaging().getCurrentPage() >= model.getData().getPaging().getLastPage()
//                                                && "1".equals(model.getData().getMore_tipoff().getIs_turn_more_tipoff())){
//                                            tvBaoLiaoJump.setVisibility(View.VISIBLE);
//                                        }else {
//                                            tvBaoLiaoJump.setVisibility(View.GONE);
//                                        }
//                                    }else {
//                                        closeStateView();
//                                    }
//                                } else {
//                                }
//
//                                Log.w(TAG,"status "+model.getData().getPaging().getCurrentPage()+"    "+model.getData().getPaging().getLastPage());
//                                componentItem.setNavigate_id(Integer.parseInt(model.getData().getMore_tipoff().getTurn_more_tipoff_navigateid()));
//                                String navigate = "{navigate:"+model.getData().getMore_tipoff().getNavigate()+"}";
//                                componentItem.orginDataObject = new JSONObject(navigate);
//                                componentItem.title = componentItem.orginDataObject.optJSONObject("navigate").getString("name");
//                            }else {
//                                showStateView(TYPE_NO_CONTENT,false);
//                            }
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        ptrLayout.setEnableLoadMore(true);
//                        ptrLayout.setEnableRefresh(true);
//                        ptrLayout.finishRefresh();
//                        ptrLayout.finishLoadMore();
//                        if (page == 1) {
//                            showStateView(TYPE_NET_NOT_GIVE_FORCE,false);
//                            tvBaoLiaoJump.setVisibility(View.VISIBLE);
//                        }else {
//                            closeStateView();
//                        }
//                    }
//                });

    }

    private String replaceString(String keyString) {
        return "<font color=\"" + AppFactoryGlobalConfig.getAppServerConfigInfo(getContext()).getColor() + "\" font-size=\"16px\">" + keyString + "</font>";
    }


    @Override
    public void onClick(int position) {
        NewBaoLiaoListModel.DataBean.PageRecordsBean data = adapter.getData(position);
        Intent intent = new Intent(getActivity(), BaoLiaoDetailActivity.class);
        intent.putExtra("id", Long.valueOf(data.getId()));
        intent.putExtra("status", data.getStatus());
        getContext().startActivity(intent);
//        if (data.getMaterialType().equals("2")) {
//            BaoLiaoMeta meta = new BaoLiaoMeta();
//            meta.setId(data.getId());
//            meta.setAvatar(data.getAvatar());
//            meta.setNickName(data.getNickName());
//            List<String> videoUrl = new ArrayList<>();
//            for (int i = 0; i < data.getShortTitleStyle().size(); i++) {
//                if(data.getShortTitleStyle().get(i).getType().equals("video")){
//                    videoUrl.add(data.getShortTitleStyle().get(i).getImgpath());
//                }
//            }
//            meta.setVideo(videoUrl);
//            meta.setContent(data.getContent());
//            meta.setCommentCount((int) data.getHitcount());
//
//            Intent intent = new Intent(getContext(), BaoLiaoVideoDetailActivity.class);
//            Bundle bundle = new Bundle();
//            bundle.putParcelable("meta", meta);
//            bundle.putInt("catalog_id", data.getCatalogId());
//            intent.putExtras(bundle);
//            getContext().startActivity(intent);
//        } else if(data.getMaterialType().equals("0")){
//            try {
//                JSONArray jsonArray = new JSONArray();
//                for (int i = 0; data.getShortTitleStyle() != null && i < data.getShortTitleStyle().size(); i++) {
//                    JSONObject jsonObject = new JSONObject();
//                    jsonObject.put("info", data.getContent());
//                    jsonObject.put("src", data.getShortTitleStyle().get(i).getImgpath());
//                    jsonArray.put(jsonObject);
//                }
//                final ArticleItem imgArticle = new ArticleItem();
//                imgArticle.setTitle(data.getContent());
//                imgArticle.setImage(jsonArray.toString());
//                imgArticle.setType(TypeX.NEWS.PHOTOS);
//                int imgIndex = position;
//                if (data.getShortTitleStyle() != null) {
//                    imgIndex -= data.getShortTitleStyle().size();
//                }
//                NewsItemClickUtils.OpenItemNewsHandle(getContext(), TypeX.NEWS.PHOTOS, imgArticle, new CatalogItem(), imgIndex, true);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }else {
//            Intent intent = new Intent(getActivity(), BaoLiaoDetailActivity.class);
//            intent.putExtra("id", data.getId());
//            intent.putExtra("status", data.getStatus());
////            intent.putExtra("url", data.getShareHtml());
//            getContext().startActivity(intent);
//        }
    }
}